//
// Created by none98 on 2021/9/22.
//

#include <spdlog/spdlog.h>
#include "Context.h"
#include "GameServer.h"
#include "PlayerBin.h"
#include "boost/asio.hpp"

Context::Context(GameServer *server) :
    uid(0),
    created(false),
    server(server),
    playBin(new PlayerBin)
{

}

void Context::Register(long uid, TcpConnectionPtr conn) {
    server->Login(uid,conn);
}

void Context::SumbitTask(const std::function<void()> &func) {
    server->SubmitTask(func);
}

sql::Connection *Context::GetDbConnection() {
    return server->dbConnectionsPool->GetConnection();
}

void Context::CloseDbConnection(sql::Connection *conn) {
    server->dbConnectionsPool->CloseConnection(conn);
}


void Context::Synchronize(){
    if(uid<=0)
        return;
    if(!created)
        return ;
    auto sqlConn = GetDbConnection();
    //set loginRes
    try {
        spdlog::info("uid:{} synchronized data",GetUid());
        if(GetPlayerBin()->GetName()!=""){
            std::vector<int> position = std::move(GetPlayerBin()->GetPosition()->Get());
            std::string sql = "UPDATE game_user_role set x=?, y=?, z=? where uid=? and rolename=?";
            std::unique_ptr <sql::PreparedStatement> statement(sqlConn->prepareStatement(sql));
            statement->setInt(1,position[0]);
            statement->setInt(2,position[1]);
            statement->setInt(3,position[2]);
            statement->setInt64(4,GetUid());
            statement->setString(5,GetPlayerBin()->GetName());
            statement->executeUpdate();
        }
        std::string updateUserSql = "UPDATE game_user set created=? where uid=?";
        std::unique_ptr <sql::PreparedStatement> statement1(sqlConn->prepareStatement(updateUserSql));
        statement1->setBoolean(1,true);
        statement1->setInt64(2,GetUid());
        statement1->executeUpdate();
    }catch(sql::SQLException &e){
        spdlog::error("uid:{},{}",GetUid(),e.what());
    }
    CloseDbConnection(sqlConn);

}
